/**
 * 初始化问题详情对话框
 */
var WzQuestionInfoDlg = {
    choice: 64,
    count: $("#itemSize").val(),
    answer: '',
    answerIds: '',//添加修改时所有ID
    answerId: '',//删除时单个ID
    itemTemplate: $("#itemTemplate").html(),//广告问题
    itemTemplate_1: $("#itemTemplate_1").html(),//调查、商家问卷
    picIds: '',//选项中图片的ID
    wzQuestionInfoData: {},
    validateFields: {
        question: {
            validators: {
                notEmpty: {
                    message: '问题不能为空'
                },
                stringLength: {
                    max: 30,
                    message: '问题长度不能多于30个字'
                }

            }
        },
        type: {
            validators: {
                notEmpty: {
                    message: '类型不能为空'
                }
            }
        }
    }
};

/**
 * 清除数据
 */
WzQuestionInfoDlg.clearData = function () {
    this.wzQuestionInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
WzQuestionInfoDlg.set = function (key, val) {
    this.wzQuestionInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
WzQuestionInfoDlg.get = function (key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
WzQuestionInfoDlg.close = function () {
    parent.layer.close(window.parent.WzQuestion.layerIndex);
}

/**
 * 收集数据
 */
WzQuestionInfoDlg.collectData = function () {
    this
        .set('questionId')
        .set('question')
        .set('type')
        .set('questionType')
        .set('publishingType');
    var type = $("#type option:selected").val()//问题类型
    var questionType = $("#questionType option:selected").val();//问题形式
    if (1 == type || 3 == type) {
        var answer = "";
        var temp = 65;
        $("input[name=itemNum]").each(function () {
            answer = answer + (String.fromCharCode(temp) + ":" + $(this).val().trim() + ";");
            temp++;
        });
        this.answer = answer;
    } else {
        var answer = "";
        var temp = 65;
        $("input[name=itemNum]").each(function () {
            answer = answer + (String.fromCharCode(temp) + ":" + $(this).val().trim() + ";");
            temp++;
        });
        this.answer = answer;
        //正确答案
        var choice = $("input[name='answer']:checked").attr('id');
        choice = String.fromCharCode(choice);
        this.answer = answer + "correctAnswer:" + choice + ";";
    }
    if (2 == questionType) {
        var picIds = "";
        $("input[type=pic]").each(function () {
            picIds = picIds + $(this).val().trim() + ";";
        });
        this.picIds = picIds;
    }
}

/**
 * 验证数据是否为空
 */
WzQuestionInfoDlg.validate = function () {
    $('#wzQuestionInfoForm').data("bootstrapValidator").resetForm();
    $('#wzQuestionInfoForm').bootstrapValidator('validate');
    return $("#wzQuestionInfoForm").data('bootstrapValidator').isValid();
};

/**
 * 提交添加
 */
WzQuestionInfoDlg.addSubmit = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    var num = $("input[name='itemNum']").length;
    if (num < 2) {
        Feng.error("填加失败，请至少添加两个选项！")
        return;
    }
    var bl = true;
    $("input[name='itemNum']").each(function () {
        if ($(this).val() == "") {
            Feng.error("内容不能为空!");
            $(this)[0].focus();
            bl = false;
        }
        var i = $(this).val().trim();
        $("input[name='itemNum']").not($(this)).each(function () {
            if ($(this).val().trim() == i && $(this).val().trim() != "") {
                $(this).css("background", "pink");
                $(this)[0].focus();
                Feng.error("有相同选项！");
                bl = false;
                return false;
            }
            return true;
        });
    });
    if (!bl) {
        return false;
    }
    var type = $("#type option:selected").val()//问题类型
    if (5 == type || 6 == type) {
        var choice = $("input[name='answer']:checked").attr('id');
        if (choice == null) {
            Feng.error("请选择正确答案！")
            return false;
        }
    }
    //判断问题是否重复（未完成）
    // var ajax = new $ax(Feng.ctxPath + "/wzQuestion/check", function (data) {
    //     Feng.error(data);
    //     return;
    // }, function (data) {
    //     Feng.error("添加失败!" + data.responseJSON.message + "!");
    // });
    // ajax.set(this.wzQuestionInfoData);
    // ajax.start();
    var questionType = $("#questionType option:selected").val();//问题形式

    // 提交信息
    var ajax = new $ax(Feng.ctxPath + "/wzQuestion/add", function (data) {
        if (data.code == 100) {
            Feng.error(data.message);
        } else if (data.code == 200) {
            Feng.success(data.message);
            window.parent.WzQuestion.table.refresh();
            WzQuestionInfoDlg.close();
        }
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });

    ajax.set(this.wzQuestionInfoData);
    ajax.set('answer', this.answer);
    ajax.set('questionType', questionType);
    if (questionType == 2) {
        var picIds = "";
        $("input[type=pic]").each(function () {
            picIds = picIds + $(this).val().trim() + ";";
        });
        this.picIds = picIds;
        ajax.set('picIds', this.picIds);
    }
    ajax.start();
}


/**
 * 提交修改
 */
WzQuestionInfoDlg.editSubmit = function () {

    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    var type = $("#type").val()//问题类型
    if (5 == type || 6 == type) {
        var choice = $("input[name='answer']:checked").attr('id');
        if (choice == null) {
            Feng.error("请选择正确答案！")
            return false;
        }
        var answerIds = '';
        $("input[id=answerId]").each(function () {
            answerIds = answerIds + $(this).val() + ";";
        });
        this.answerIds = answerIds;
    } else {
        var answerIds = '';
        $("input[id=answerId_1]").each(function () {
            answerIds = answerIds + $(this).val() + ";";
        });
        this.answerIds = answerIds;
    }
    var bl = true;
    $("input[name='itemNum']").each(function () {
        if ($(this).val() == "") {
            Feng.error("内容不能为空!");
            $(this)[0].focus();
            bl = false;
        }
        var i = $(this).val().trim();
        $("input[name='itemNum']").not($(this)).each(function () {
            if ($(this).val().trim() == i && $(this).val().trim() != "") {
                $(this).css("background", "pink");
                $(this)[0].focus();
                Feng.error("有相同选项！");
                bl = false;
                return false;
            }
            return true;
        });
    });
    if (!bl) {
        return false;
    }
    var questionType = $("#questionType").val();//问题形式
    var ajax = new $ax(Feng.ctxPath + "/wzQuestion/update", function (data) {
        if (data.code == 100) {
            Feng.error(data.message);
        } else if (data.code == 200) {
            Feng.success(data.message);
            window.parent.WzQuestion.table.refresh();
            WzQuestionInfoDlg.close();
        }
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.wzQuestionInfoData);
    ajax.set('answer', this.answer);
    ajax.set('answerIds', this.answerIds);
    if(2==questionType){
        ajax.set('picIds', this.picIds);
    }
    ajax.start();
}

$(function () {
    Feng.initValidator("wzQuestionInfoForm", WzQuestionInfoDlg.validateFields);
});


/**
 * item获取新的id
 */
WzQuestionInfoDlg.newId = function () {
    if (this.count == undefined) {
        this.count = 0;
    }
    this.count = this.count + 1;
    return "dictItem" + this.count;
};
/**
 * choice获取新的choice
 */

WzQuestionInfoDlg.newChoice = function () {
    this.choice = this.choice + 1;
    return this.choice;
};

/**
 * 关闭此对话框
 */
WzQuestionInfoDlg.close = function () {
    parent.layer.close(window.parent.WzQuestion.layerIndex);
};

/**
 * 添加条目
 */
var count = 1;
WzQuestionInfoDlg.addItem = function () {
    var type = $("#type option:selected").val()//问题类型
    var questionType = $("#questionType option:selected").val();//问题形式
    if (!this.validate()) {
        return;
    } else
    if (1 == type || 3 == type) {//调查、商家问卷
        var i = $("input[id=answer]").length;
        if (i >= 1) {
            Feng.error("增加失败，请选择正确问题类型");
            $("#type").css("background", "pink");
            $("#type").focus();
            return;
        }else{
            $("#type").css("background", "white");
        }
        if (questionType == 1) {
            var j = $("div[name=answerAndPic_1]").length;
            if (j >= 1) {
                Feng.error("增加失败，请选择正确问题形式");
                $("#questionType").css("background", "pink");
                $("#questionType").focus();
                return;
            }else{
                $("#questionType").css("background", "white");
            }
            $("#itemsArea").append(this.itemTemplate_1);
            $("#dictItem_1").attr("id", this.newId());
        } else {
            var i = $("input[id=answer_1]").length;
            if (i >= 1) {
                Feng.error("增加失败，请选择正确问题类型");
                $("#questionType").css("background", "pink");
                $("#questionType").focus();
                return;
            }else{
                $("#questionType").css("background", "white");
            }
            var j = $("div[name=answerAndPic]").length;
            if (j >= 1) {
                Feng.error("增加失败，请选择正确问题类型");
                $("#type").css("background", "pink");
                $("#type").focus();
                return;
            }else{
                $("#type").css("background", "white");
            }
            var answerAndPic = "<div class=\"form-group\" name=\"answerAndPic_1\" style=\"margin-top: 10px\" id=\"answerAndPic" + count + "\">" +
                "<div>" +
                "        <label class=\"col-sm-2 control-label\">答案</label>\n" +
                "        <div   style='margin-bottom: 1.03%' class=\"col-sm-10\">\n" +
                "            <input type=\"title\" class=\"form-control\" name=\"itemNum\" id=\"text\"\n" +
                "                   style=\"width: 70%;\" >\n" +
                "        </div>\n" +
                " </div>" +
                "<div>" +
                "        <label class=\"col-sm-2 control-label\">图片id</label>\n" +
                "        <div class=\"col-sm-10\" >\n" +
                "            <input type=\"pic\" class=\"form-control\" id=\"fileId\"\n" +
                "                   style=\"width: 20%;\" >\n" +
                "        </div>" +
                " </div>" +
                "        <div class=\"col-sm-9\" style=\"margin-top:16px;margin-left: 140px \">\n" +
                "                    <img id=\"previewPic\" src=\"\" width=\"130\" height=\"160\" style=\"margin:-8px auto;display:none\" />\n" +
                "        </div>"+
                "<div style='margin-left: 16.7%'><button style='margin-top: 0.8%' type=\"button\" class=\"btn btn-danger button-margin\"  onclick=\"WzQuestionInfoDlg.deleteItem(event)\" id=\"\">\n" +
                "    <i class=\"fa fa-remove\"></i>&nbsp;删除\n" +
                "</button></div>" +
                "</div>";
            $("#itemsArea").append(answerAndPic);
            count+=1;
        }
    } else if (2 == type) {//广告问题
        var i = $("input[id=answer_1]").length;
        if (i >= 1) {
            Feng.error("增加失败，请选择正确问题类型");
            $("#type").css("background", "pink");
            $("#type").focus();
            return;
        }else{
            $("#type").css("background", "white");
        }
        if (questionType == 1) {
            var j = $("div[name=answerAndPic]").length;
            if (j >= 1) {
                Feng.error("增加失败，请选择正确问题形式");
                $("#questionType").css("background", "pink");
                $("#questionType").focus();
                return;
            }else{
                $("#questionType").css("background", "white");
            }
            $("#itemsArea").append(this.itemTemplate);
            $("#dictItem").attr("id", this.newId());
            $("#choice").attr("id", this.newChoice());
        } else {
            var i = $("input[id=answer]").length;
            if (i >= 1) {
                Feng.error("增加失败，请选择正确问题类型");
                $("#questionType").css("background", "pink");
                $("#questionType").focus();
                return;
            }else{
                $("#questionType").css("background", "white");
            }
            var j = $("div[name=answerAndPic_1]").length;
            if (j >= 1) {
                Feng.error("增加失败，请选择正确问题类型");
                $("#type").css("background", "pink");
                $("#type").focus();
                return;
            }else{
                $("#type").css("background", "white");
            }
            var choice = 64 + count;
            var answerAndPic = "<div class=\"form-group\" name=\"answerAndPic\" style=\"margin-top: 10px\" id=\"answerAndPic" + count + "\">" +
                "<div>" +
                "        <label class=\"col-sm-2 control-label\">答案</label>\n" +
                "        <div   style='margin-bottom: 1.03%' class=\"col-sm-10\">\n" +
                "            <input type=\"title\" class=\"form-control\" name=\"itemNum\" id=\"text\"\n" +
                "                   style=\"width: 70%;\" >\n" +
                "        </div>\n" +
                " </div>" +
                "<div>" +
                "        <label class=\"col-sm-2 control-label\">图片id</label>\n" +
                "        <div class=\"col-sm-10\" >\n" +
                "            <input type=\"pic\" class=\"form-control\" id=\"fileId"+count+"\"\n" +
                "                   style=\"width: 20%;\" >\n" +
                "           <div style='margin-top: -3.6%;margin-left: 31.3%'>" +
                "               <label>正确</label>" +
                "               <input  type=\"radio\" name=\"answer\" id=" + choice + "\>" +
                "           </div>" +
                "        </div>" +
                " </div>" +
                "        <div class=\"col-sm-9\" style=\"margin-top:16px;margin-left: 140px \">" +
                "         <image id=\"previewPic"+count+"\"  src=\"\" width=\"130\" height=\"160\" style=\"margin:-8px auto;display:none\" />" +
                "        </div>"+
                "<div style='margin-left: 16.7%;'><button  style='margin-top: -1.2%' type=\"button\" class=\"btn btn-danger button-margin\"  onclick=\"WzQuestionInfoDlg.deleteItem(event)\" id=\"\">\n" +
                "    <i class=\"fa fa-remove\"></i>&nbsp;删除\n" +
                "</button></div>" +
                "</div>";
            $("#itemsArea").append(answerAndPic);
            // $("#fileId"+count).mouseleave(function(){
            //     var picId=$(this).val().trim();
            //     var ajax = new $ax(Feng.ctxPath + "/pfFile/getUrl", function (data) {
            //         if(data.code == 100){
            //             Feng.error(data.message);
            //         }else{
            //             // Feng.info(data);
            //             $("#previewPic"+count).css("display","");
            //             Feng.info("???????????1");
            //             $("#previewPic"+count).attr("src",data);
            //             Feng.info("???????????2");
            //         }
            //     }, function (data) {
            //     });
            //     ajax.set("picId",picId);
            //     ajax.start();
            // });
            count += 1;
        }
    }
};

/**
 * 删除item
 */
WzQuestionInfoDlg.deleteItem = function (event) {
    var obj = Feng.eventParseObject(event);
    obj = obj.is('button') ? obj : obj.parent();
    obj.parent().parent().remove();
};
/**
 * 删除答案
 */
WzQuestionInfoDlg.deleteAnswer = function (event, answerId, id) {
    var checked = $("input[name='answer']:checked").attr('id');
    if (checked == id) {
        Feng.error("无法删除正确答案！");
        return false;
    }
    this.answerId = answerId;
    this.clearData();
    this.collectData();
    var num = $("input[name='itemNum']").length;
    if (num <= 2) {
        Feng.error("删除失败，至少要有两个选项！")
        return;
    }
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/wzQuestion/deleteAnswer", function (data) {
            var obj = Feng.eventParseObject(event);
            obj = obj.is('button') ? obj : obj.parent();
            obj.parent().parent().remove();
            Feng.success("删除成功!");
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.wzQuestionInfoData);
        ajax.set('answerId', WzQuestionInfoDlg.answerId);
        ajax.start();
    };
    Feng.confirm("是否刪除该答案?", operation);
};

WzQuestionInfoDlg.deleteAnswer_1 = function (event, answerId) {
    this.answerId = answerId;
    this.clearData();
    this.collectData();
    var num = $("input[name='itemNum']").length;
    if (num <= 2) {
        Feng.error("删除失败，至少要有两个选项！")
        return;
    }
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/wzQuestion/deleteAnswer", function (data) {
            var obj = Feng.eventParseObject(event);
            obj = obj.is('button') ? obj : obj.parent();
            obj.parent().parent().remove();
            Feng.success("删除成功!");
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set(this.wzQuestionInfoData);
        ajax.set('answerId', WzQuestionInfoDlg.answerId);
        ajax.start();
    };
    Feng.confirm("是否刪除该答案?", operation);
};
/**
 * 清除为空的item Dom
 */
WzQuestionInfoDlg.clearNullDom = function () {
    $("[name='dictItem']").each(function () {
        var num = $(this).find("[name='itemNum']").val();
        var name = $(this).find("[name='itemName']").val();
        if (num == '' || name == '') {
            $(this).remove();
        }
    });
};


